package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.User;

import service.UserService;
import sun.rmi.server.UnicastServerRef;

public class Home extends HttpServlet {

	UserService userService=new UserService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action=request.getParameter("action");
		if(action!=null && action.equals("logout"))
		{
			HttpSession session = request.getSession();
			if(session!=null)
				session.invalidate();			
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/home.jsp");
		if (dispatcher != null) dispatcher.forward(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email=request.getParameter("email");
		String password=request.getParameter("password");
		
		User user=userService.authenticateUser(email, password);
		
		if(user!=null)
		{
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
		}
		else
		{
			request.setAttribute("error", "Invalid username or password!");
		}		
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/home.jsp");
		 if (dispatcher != null) dispatcher.forward(request, response);
	}

}
